<?php

namespace plugin\tuPay\app\controller;

use plugin\tuPay\app\services\ConfigService;
use support\Request;
use support\Response;
use plugin\tuPay\app\model\TupayConfig;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;
use app\common\services\DragdoneUpService;

/**
 * 支付配置 
 */
class TupayConfigController extends Crud
{

    /**
     * @var TupayConfig
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new TupayConfig;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(Request $request): Response
    {
        // 将url参数传递给前端
        // \support\View::assign(['params'=>$request->get()]);
        return view('tupay-config/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $data = $this->insertInput($request);
            $data['alias'] = ConfigService::getPayConfig($data['name']);
            $id = $this->doInsert($data);
            return $this->json(0, 'ok', ['id' => $id]);
        }
        return view('tupay-config/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
                    // 拖拽排序更新
            if($request->post('dragDone')==1 && DragdoneUpService::dragDoneUpData($request,$this->model)){
                return $this->json(0,'ok');
            }
            [$id, $data] = $this->updateInput($request);
            $data['alias'] = ConfigService::getPayConfig($data['name']);
            $this->doUpdate($id, $data);
            return $this->json(0);
        }
        return view('tupay-config/update');
    }

    // 设置配置信息
    public function setConfig(Request $request): Response{
        $id = $request->get('id');
        $name = strtolower($request->get('name'));
        if($request->method() == 'POST'){
            $params = $request->post();
            $data = [
                'config'=>json_encode($params,256),
                'updated_at'=>date('Y-m-d H:i:s'),
            ];
            $id = $params['id'];
            TupayConfig::where(['id'=>$id])->update($data);
            return $this->json(0);
        }

        $config = TupayConfig::where(['id'=>$id])->value('config');
        if($config){
            $config = json_decode($config,1);
        }
        return view('pay-type/'.$name,[
            'id'=>$id,
            'config'=>$config
        ]);
    }

}
